var entityCollection = require('../../../Base/server/controllers/EntityCollection'),
    _ = require('lodash'),
    Q = require('q'),
    BarcodeEnum = require('../../../Barcode/server/controllers/Enum.server.controller'),
    QCEnum = require('../../../QC/server/controllers/Enum.server.controller'),
    OperationController = require('../../../CBO/server/controllers/Operation.server.controller'),
    BizRecordController = require('../../../Barcode/server/controllers/BizRecord.server.controller.js'),
    BaseFun = require('../../../Base/server/controllers/Function');

exports.createByBizRecord = function(bizRecordId) {
    return new Promise(function(resolve, reject) {
        var entity = entityCollection.getEntity("BizRecord");
        BizRecordController.findByPeriodOutput(bizRecordId).then(function(bizRecord) {
            if (bizRecord) {
                //只有是物料条码才写作业产量
                if (bizRecord.BarcodeMaster.BarcodeType == BarcodeEnum.BarcodeType.ItemMaster.Value) {
                    //有返工工序的不记录
                    if (!bizRecord.BarcodeMaster.QCReworkOperation) {
                        bizRecord.BizDate = new Date(bizRecord.CollectDateTime.getFullYear(), bizRecord.CollectDateTime.getMonth(), bizRecord.CollectDateTime.getDate(), 0, 0, 0);
                        //创建作业产量数据
                        var workRecord = {
                            Work: bizRecord.Work,
                            ItemMaster: bizRecord.BarcodeMaster.ItemMaster,
                            Department: bizRecord.WorkLocation.Department,
                            BizDate: bizRecord.BizDate,
                            DescSeg1: bizRecord.BarcodeMaster.DescSeg1,
                            DescSeg2: bizRecord.BarcodeMaster.DescSeg2,
                            DescSeg3: bizRecord.BarcodeMaster.DescSeg3,
                            CompleteQty: 0, //当期产量
                            ReworkQty: 0, //当期返工:传入的返工量
                            ScriptQty: 0, //当期报废:传入的报废量。
                            Users: bizRecord.Users
                        };

                        //注：由于现在流水记录还没有批量，全按数量1处理
                        if (bizRecord.QCStatus == QCEnum.QCStatus.Rework.Value) { //返工
                            workRecord.ReworkQty = 1;
                        } else if (bizRecord.QCStatus == QCEnum.QCStatus.Scrap.Value) { //报废
                            workRecord.ScriptQty = 1;
                        }

                        //如果是计时工序
                        if (bizRecord.BarcodeMaster.Operation.IsTiming) {
                            //按“工序ID+条码主档ID”到“条码流水档”中查找记录，如果只有一条，则结束。（因为对计时工序，只在第二次刷芯片时记录）
                            entity.find({ BarcodeMaster: bizRecord.BarcodeMaster._id, Operation: bizRecord.Operation }, null, null, function(err, records) {
                                if (!err) {
                                    if (records.length === 2) {
                                        workRecord.CompleteQty = 1;
                                        exports.createWorkRecord(bizRecord.Users, workRecord, function(err, data) {
                                            if (err) {
                                                reject(err);
                                            } else {
                                                resolve(true);
                                            }
                                        });
                                    } else {
                                        resolve(true);
                                    }
                                } else {
                                    reject(err);
                                }
                            });
                        } else {
                            workRecord.CompleteQty = 1;
                            exports.createWorkRecord(bizRecord.Users, workRecord, function(err, data) {
                                if (err) {
                                    reject(err);
                                } else {
                                    resolve(true);
                                }
                            });
                        }
                    }
                } else {
                    resolve(true);
                }
            }
        });
    });
};

exports.createWorkRecord = function(users, workRecord, completeFun) {
    operationWorkOutput(workRecord).then(function() {
        if (completeFun) {
            completeFun(null, true);
        }
    }, function(err) {
        if (completeFun) {
            completeFun(err);
        }
    });

};
exports.queryWorkRecord = function(condition, completeFun) {
    var entity = entityCollection.getEntity('WorkOutput');
    if (!condition) {
        condition = {};
    }
    entity.find(condition, null, [{
        path: 'Department',
        select: 'Code Name'
    }, {
        path: 'User',
        select: 'Code Name'
    }, {
        path: 'Work',
        select: 'Code Name'
    }, {
        path: 'ItemMaster',
        select: 'Code Name'
    }], function(err, records) {
        if (err) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询错误';
            newErr.message = '查询作业报表失败！';
            completeFun(newErr);
        } else {
            completeFun(null, records);
        }
    });
}

//通过时间段查找作业产量(按时间降序)
exports.getWorkOutputByDate = function(startDay, endDay, department, completeFun) {

    var entity = entityCollection.getEntity("WorkOutput");
    entity.find({
        BizDate: { $gte: startDay + " 00:00:00", $lte: endDay + " 23:59:59" },
        Department: department
    }, { BizDate: -1 }, [{
        path: "ItemMaster",
        select: "Code Name"
    }, {
        path: 'Work',
        select: 'Code Name'
    }], function(err, records) {
        if (err) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询错误';
            newErr.message = '查询作业产量表失败！';
            completeFun(newErr);
        } else {
            completeFun(null, records);
        }
    });
};


//根据部门和时间段查找作业产量
//按照作业和物料分类
exports.queryWorkOutputByIW = function (startDay, endDay, dpt, completeFun) {
    
    var entity = entityCollection.getEntity("WorkOutput");

    var workOutputQuery = {
        Department: dpt,
        BizDate: { $gte: startDay + " 00:00:00", $lte: endDay + " 23:59:59" }
    };

    var workOutputMap = function () {
        emit({'ItemMaster': this.ItemMaster, 'Work': this.Work}, {workOutputs: [this]});
    };

    var workOutputReduce = function (key, values) {
        var res = {
            workOutputs: []
        };
        values.forEach(function(val) {
            val.workOutputs.forEach(function(obj) {
                res.workOutputs.push(obj);
            });
        });
        return res;
    };

    var option = {
        query: workOutputQuery,
        map: workOutputMap,
        reduce: workOutputReduce
    };

    entity.mapReduce(option, null, null, function (err, result) {
        if (err) {
            completeFun(err);
        } else {
            completeFun(err, result);
        }
    });
    
}
 

function operationWorkOutput(workRecord) {
    var deferred = Q.defer();
    var entity = entityCollection.getEntity('WorkOutput');
    entity.findOne({
        Work: workRecord.Work,
        ItemMaster: workRecord.ItemMaster,
        Department: workRecord.Department,
        Users: workRecord.Users,
        BizDate: workRecord.BizDate, //时间必须是0:00:00
        DescSeg1: workRecord.DescSeg1,
        DescSeg2: workRecord.DescSeg2,
        DescSeg3: workRecord.DescSeg3
    }, null, function(err, record) {
        if (!err) {
            if (record) {
                //如果有，更新
                record.ReworkQty += workRecord.ReworkQty;
                record.ScriptQty += workRecord.ScriptQty;
                record.CompleteQty += workRecord.CompleteQty;
                //修改车间期间产量
                entity.update(record, function(err, result) {
                    if (err) {
                        BaseFun.errorLog('更新车间期间产量错误', err.message);
                        deferred.reject(err);
                    } else {
                        deferred.resolve(true);
                    }
                });
            } else {
                //没找到则新增
                entity.insert(workRecord, function(err, record) {
                    if (err) {
                        BaseFun.errorLog('创建车间期间产量错误', err.message);
                        deferred.reject(err);
                    } else {
                        deferred.resolve(true);
                    }
                });
            }
        }
    });
    return deferred.promise;
}


//聚合查找作业产量库
exports.workOutputAggregate = function(args, completeFun) {
    var entity = entityCollection.getEntity("WorkOutput");
    entity.Entity.aggregate(args, function(err, records) {
        if (err) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询作业产量错误';
            newErr.message = '查询作业产量错误, 请检查查询参数！';
            completeFun(newErr);
        } else {
            completeFun(null, records);
        }
    });

};

